import { createElement, ReactElement } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import PositionSelector from '../components/PositionSelector';

function mountModalToBody(node: ReactElement) {
  const wrapper = document.createElement('div', {});
  document.body.appendChild(wrapper);
  render(node, wrapper);
  return {
    unmount() {
      try {
        unmountComponentAtNode(wrapper);
        wrapper?.remove?.();
      } catch (e) {}
    },
  };
}

export const positionSelector = (params: { users: string[]; onOk: Function }) => {
  const { unmount } = mountModalToBody(
    createElement(PositionSelector, {
      ...params,
      visible: true,
      onCancel: () => {
        unmount();
      },
      onOk: async ({ form }) => {
        await form.validateFields().then((res: any) => {
          params?.onOk(res);
          unmount();
        });
      },
    }),
  );
};
